<?php
/**
 * Created by PhpStorm.
 * User: zyw
 * Date: 2018-06-22
 * Time: 22:39
 */

try{
    set_time_limit(0);
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Asia/Shanghai');
    require_once "../../db/video_db.php";

    $postData = file_get_contents('php://input');
    $data = json_decode($postData, true);

    $pattern = '/(\s)+/is';
    $uid = isset($data["uid"]) ? $data["uid"] : 0;
    $title = isset($data["title"]) ? $data["title"] : "";
    $title = trim($title);
    $title = preg_replace($pattern, "\n", $title);

    $desc = isset($data["desc"]) ? $data["desc"] : "";
    $desc = trim($desc);
    $desc = preg_replace($pattern, "\n", $desc);

    $type = 2;
    $source = isset($data["source"]) ? $data["source"] : "";
    $city = isset($data["city"]) ? $data["city"] : array(); //{"city":"城市名称", "location":"位置名称", "lon":"经度", "lat":"纬度"}
    $pics = isset($data["pics"]) ? $data["pics"] : array();// [{"u":"url","w":"宽度","h":"高度","s":"大小"}]
    $music_id = isset($data["music_id"]) ? $data["music_id"] : "";
    $video = isset($data["video"]) ? $data["video"] : array(); //{"video_address":"地址", "video_time":"时长"}
    $add_time = !empty($data["add_time"]) ? $data["add_time"] : "";
    $topic = isset($data["topic"]) ? $data["topic"] : ""; //话题名称
    $like_num = isset($data["like_num"]) ? $data["like_num"] : 0;//点赞数
    $is_side = isset($data["is_side"]) ? $data["is_side"] : 0;//是否横屏

    if(empty($title) || empty($desc)){
        $res = array("code"=>-1, "result"=>null, "msg"=>"标题和描述不能为空");
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    $title = str_replace('\'', '', $title);
    $desc = str_replace('\'', '', $desc);
    if(!empty($city)){
        if(empty($city["city"]) || empty($city["location"]) || empty($city["lon"]) || empty($city["lat"])){
            $res = array("code"=>-1, "result"=>null, "msg"=> '城市数据格式不正确, 例: {"city":"城市名称", "location":"位置名称", "lon":"经度", "lat":"纬度"}');
            echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
        }
    }
    if(!empty($pics)){
        foreach($pics as $p){
            if(empty($p["u"]) || empty($p["w"]) || empty($p["h"])){
                $res = array("code"=>-1, "result"=>null, "msg"=>  '图片列表数据格式不正确,例: [{"u":"url","w":"宽度","h":"高度","s":"大小"}]');
                echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
            }
        }
    }

    if(empty($video["video_address"]) || empty($video["video_time"]) ){
        $res = array("code"=>-1, "result"=>null, "msg"=>  '视频数据格式不正确, 例: {"video_address":"地址", "video_time":"时长"}');
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    $sql = 'select count(*) as num from t_user where uid='.$uid;
    $uNum = video_db::fetch($sql);
    if($uNum["num"] <= 0){
        $res = array("code"=>-1, "result"=>null, "msg"=>"用户不存在");
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    $city_id = 0;
    if(!empty($city)){
        $sql = "select * from t_district where `name` like '%".$city["city"]."' limit 1";
        $district = video_db::fetch($sql);
        $city_id = !empty($district["id"]) ? $district["id"] : 0;
    }
    $sql = "insert into t_video(video_address, video_time, is_side, add_time)values('".$video["video_address"]."', '".$video["video_time"]."', ".$is_side.", '".time()."')";
    $video_id = video_db::execute($sql);

    $add_time = empty($add_time) ? time() : $add_time;
    $music_id = (int)$music_id;$city_id = (int)$city_id;$location=@(string)$city["location"];$lon = empty($city["lon"]) ? "" : $city["lon"];
    $lat = empty($city["lat"]) ? "" : $city["lat"];
    $sql = "insert into t_post(uid,title,`desc`,add_time,video_id,music_id,city_id,location,lon,lat,`type`,source,status,v_like_num) values
('".$uid."','".$title."','".$desc."','".$add_time."','".$video_id."','".$music_id."','".$city_id."','".$location."','".$lon."','".$lat."','".$type."','".$source."',1,'".$like_num."')";
    $post_id = video_db::execute($sql);

    if($post_id == false){
        $res = array("code"=>-1, "result"=>null, "msg"=>"发布帖子失败！！！");
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    $code = $add_time.$post_id;
    $sql = "update t_post set code='".$code."' where id=".$post_id;
    video_db::execute($sql);

    $sql = "update t_video set post_id=".$post_id." where id=".$video_id;
    video_db::execute($sql);

    $picList = array();
    foreach($pics as $pic){
        $sql = "insert into t_img(path, w, h, `size`, add_time)values('".$pic["u"]."', '".$pic["w"]."', '".$pic["h"]."', '".@$pic["s"]."', '".time()."')";
        $imgId = video_db::execute($sql);
        $picList[] = $imgId;
    }
    $sql = "update t_post set pics='".implode(",", $picList)."' where id=".$post_id;
    video_db::execute($sql);

    $sql = "update t_user_count set pub_num=pub_num+1 where uid=".$uid;
    video_db::execute($sql);

    if(!empty($topic)){
        $sql = "select * from t_topic where title='".$topic."' and `level`=2 limit 1";
        $topicInfo = video_db::fetch($sql);
        if(empty($topicInfo)){
            $sql = "insert into t_topic(title, `level`, parent_id)values('".$topic."', 2, 0)";
            $topic_id = video_db::execute($sql);
        }else{
            $topic_id = $topicInfo["id"];
        }
        $sql = "insert into t_post_topic(post_id, topic_id)values(".$post_id.", ".$topic_id.")";
        video_db::execute($sql);

        $sql = "update t_topic set post_num=post_num+1 where id=".$topic_id;
        video_db::execute($sql);
    }
    video_db::close();
    $res = array("code"=>0, "result"=>array("post_id" => $post_id), "msg"=>"");
    echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;

}catch(PDOException $pe){
    video_db::close();
    file_put_contents('../log/error_'.date('Ymd').'.log',date("Y-m-d H:i:s")."  ".$pe->getMessage()."\r\n",FILE_APPEND);

    $res = array("code"=>-1, "result"=>null, "msg"=>$pe->getMessage());
    echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
}catch (Exception $e){
    video_db::close();
    file_put_contents('../log/error_'.date('Ymd').'.log',date("Y-m-d H:i:s")."  ".$e->getMessage()."\r\n",FILE_APPEND);

    $res = array("code"=>-1, "result"=>null, "msg"=>$e->getMessage());
    echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
}

